﻿using System;
using System.Web;
using System.Linq;
using System.Text;
using System.Web.Routing;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace Tencent.OA.App
{
    /// <summary>
    /// 提供一组用于分页的扩展方法。
    /// </summary>
    public static class PagingExtensions
    {
        private const string PAGING_ARGES_NAME = "page";

        public static MvcHtmlString Pager<TModel>(this HtmlHelper<IPager<TModel>> htmlHelper, IPager<TModel> pagedEntity)
        {
            return GeneratePagerHtml<TModel>(htmlHelper, htmlHelper.ViewContext.RequestContext, pagedEntity);
        }

        public static MvcHtmlString Pager<TModel>(this HtmlHelper htmlHelper, IPager<TModel> pagedEntity)
        {
            return GeneratePagerHtml<TModel>(htmlHelper, htmlHelper.ViewContext.RequestContext, pagedEntity);
        }

        private static MvcHtmlString GeneratePagerHtml<TModel>(HtmlHelper htmlHelper, RequestContext context, IPager<TModel> pagedEntity)
        {
            if (pagedEntity == null)
#if DEBUG
                throw new ArgumentNullException("pagedEntity");
#else
                return MvcHtmlString.Create("");
#endif

            StringBuilder html = new StringBuilder();
            UrlHelper urlHelper = new UrlHelper(context);

            int pageNumber = pagedEntity.PageNumber;
            int totalItemCount = pagedEntity.TotalItemCount;
            int totalpage = pagedEntity.PageCount;
            int currentPageIndex = pagedEntity.PageIndex;
            bool hasPreviousPage = pagedEntity.HasPreviousPage;
            bool hasNextPage = pagedEntity.HasNextPage;

            // 呈现分页信息
            html.AppendLine(GeneratePagingLink(currentPageIndex > 0, GeneratePagingLinkUrl(context, 1), "第一页", urlHelper.Content("~/content/images/pagination-first.gif")));
            html.AppendLine(GeneratePagingLink(hasPreviousPage, GeneratePagingLinkUrl(context, pageNumber - 1), "前一页", urlHelper.Content("~/content/images/pagination-prev.gif")));
            html.AppendLine(string.Format("<span class=\"page-num\">总计 {0} 记录 当前第 {1} 页共 {2} 页</span>",
                totalItemCount, pageNumber, totalpage));
            html.AppendLine(GeneratePagingLink(hasNextPage, GeneratePagingLinkUrl(context, pageNumber + 1), "下一页", urlHelper.Content("~/content/images/pagination-next.gif")));
            html.AppendLine(GeneratePagingLink(currentPageIndex < (totalpage - 1), GeneratePagingLinkUrl(context, totalpage), "最后一页", urlHelper.Content("~/content/images/pagination-last.gif")));

            // 呈现跳转
            //html.Append(htmlHelper.BeginForm(context.RouteData.Values["action"], context.RouteData.Values["controller"]).);
            html.Append("<form method=\"get\">");
            var queryString = context.HttpContext.Request.QueryString;
            foreach (var name in queryString.AllKeys)
            {
                if (!string.Equals(name, "page", StringComparison.CurrentCultureIgnoreCase))
                    html.Append(htmlHelper.Hidden(name, queryString[name]).ToString());
            }
            html.Append(" 跳至第 ");
            html.Append(htmlHelper.TextBox("page", pageNumber, new { @class = "gotoBox", style = "width:30px" }).ToString());
            html.Append(" 页 <input type=\"submit\" value=\"Go\" /></form>");
            return MvcHtmlString.Create(html.ToString());
        }

        private static string GeneratePagingLink(bool hasLink, string linkUrl, string linkText, string imageUrl)
        {
            if (hasLink)
                return string.Format("<a href=\"{0}\"><img alt=\"{1}\" src=\"{2}\" /></a>", new string[] { linkUrl, linkText, imageUrl });
            else
                return string.Format("<span class=\"nopaging\"><img alt=\"{0}\" src=\"{1}\" /></span>", new string[] { linkText, imageUrl });
        }

        private static string GeneratePagingLinkUrl(RequestContext context, int page)
        {
            HttpRequestBase req = context.HttpContext.Request;
            string url = req.FilePath;
            var queryStrings = new NameValueCollection(req.QueryString);

            if (queryStrings.AllKeys.Contains(PAGING_ARGES_NAME)) // 已有分页参数
                queryStrings[PAGING_ARGES_NAME] = page.ToString();
            else
                queryStrings.Add(PAGING_ARGES_NAME, page.ToString());

            List<string> qs = new List<string>();
            foreach (string s in queryStrings)
            {
                qs.Add(s + "=" + queryStrings[s]);
            }

            return string.Concat(new string[] { url, "?", string.Join("&", qs.ToArray()) });
        }

        /*public static string Pager(this HtmlHelper htmlHelper, int pageSize, int currentPage, int totalItemCount)
        {
            return Pager(htmlHelper, pageSize, currentPage, totalItemCount, null, null);
        }

        public static string Pager(this HtmlHelper htmlHelper, int pageSize, int currentPage, int totalItemCount, string actionName)
        {
            return Pager(htmlHelper, pageSize, currentPage, totalItemCount, actionName, null);
        }

        public static string Pager(this HtmlHelper htmlHelper, int pageSize, int currentPage, int totalItemCount, object values)
        {
            return Pager(htmlHelper, pageSize, currentPage, totalItemCount, null, new RouteValueDictionary(values));
        }

        public static string Pager(this HtmlHelper htmlHelper, int pageSize, int currentPage, int totalItemCount, string actionName, object values)
        {
            return Pager(htmlHelper, pageSize, currentPage, totalItemCount, actionName, new RouteValueDictionary(values));
        }

        public static string Pager(this HtmlHelper htmlHelper, int pageSize, int currentPage, int totalItemCount, RouteValueDictionary valuesDictionary)
        {
            return Pager(htmlHelper, pageSize, currentPage, totalItemCount, null, valuesDictionary);
        }

        public static string Pager(this HtmlHelper htmlHelper, int pageSize, int currentPage, int totalItemCount, string actionName, RouteValueDictionary valuesDictionary)
        {
            if (valuesDictionary == null)
            {
                valuesDictionary = new RouteValueDictionary();
            }
            if (actionName != null)
            {
                if (valuesDictionary.ContainsKey("action"))
                {
                    throw new ArgumentException("The valuesDictionary already contains an action.", "actionName");
                }
                valuesDictionary.Add("action", actionName);
            }
            //var pager = new Pager(htmlHelper.ViewContext, pageSize, currentPage, totalItemCount, valuesDictionary);
            //return pager.RenderHtml();
            return "";
        }*/

    }
}
